<?php
require_once ('include/check.php');
if (!$isAdmin) {
	echo "У вас нет доступа к этой странице.";
	exit();
}
$request = mysql_query("SELECT * FROM users;");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<script src="js/jquery-2.1.1.min.js" type="text/javascript"></script>
		<script src="js/json.js" type='text/javascript'></script>
		<script src="js/jquery-ui.min.js" type="text/javascript"></script>
		<script src="js/util_script.js" type="text/javascript"></script>
		<script src="js/jquery.editable.js" type="text/javascript"></script>
		<script src="js/jquery.dataTables.min.js" type="text/javascript"></script>
		<link href="css/styles.css" rel="stylesheet" type="text/css" />
		<link href="css/jquery-ui.css" rel="stylesheet" type="text/css" />
		<link href="css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
		<style type="text/css">
			#user_edit th, #user_edit td:not(:last-child) {
				text-align: left;
			}
			#user_edit tr {
				height: 30px;
			}
		</style>
		<script type="text/javascript">
			var newPass = false;
			var userId = null;
			$(document).ready(function() {
				$("button").button();
				$("#save-user").click(saveUser);
				$("#delete-user").click(deleteUser);
				$(".editable_single").editable();
				$("#user_edit").dialog({
					autoOpen : false,
					width : 400,
					height : 230,
					title : 'Пользователь'
				});
				$("#users_list").on("click","a.user-link", function() {
					$.ajax({
						method : "POST",
						url : "include/user_controller.php",
						data : {
							op : "get_user",
							id : $(this).attr("id")
						}
					}).done(function(response) {
						var result = JSON.parse(response);
						userId = result.user_id;
						newPass = null;
						$("#user-login").text(result.user_login);
						$("#is_admin").val(result.admin);
						switchControls(false);
						$("#user_edit").dialog("open");
					});
				});
				$("#create-user").click(function() {
					userId = null;
					newPass = null;
					$("#user-login").text("");
					$("#is_admin").val(0);
					switchControls(true);
					$("#user_edit").dialog("open");
					$("#user-login").trigger("click");
				});
				$("#change-pass").click(function() {
					switchControls(true);
					newPass = true;
					$("#pass").focus();
				});
			});
			function switchControls(create) {
				$("#delete-user").toggle(!create);
				$("#confirm_pass").toggle(create);
				$("#pass").toggle(create);
				$("#change-pass").toggle(!create);
				$("#pass").val(""); $("#confirm").val("");
			}

			function saveUser() {
				var error = false;
				if ( error = $("#user-login").text() == "")
					$("#login-error").show();
				else
					$("#login-error").hide();
				if (newPass || !userId) {
					if ($("#pass").val() == "") {
						$("#pass-error").show();
						error = true;
					} else
						$("#pass-error").hide();
					if ($("#confirm").val() != $("#pass").val()) {
						$("#confirm-error").show();
						error = true;
					} else
						$("#confirm-error").hide();
				}
				if (error)
					return;
				if (!userId)
					userId = guid();
				var data = {
					id: userId,
					login: $("#user-login").text(),
					pass: $("#pass").val(),
					admin: $("#is_admin").val()
				};
				$.ajax({
					method : "POST",
					url : "include/user_controller.php",
					data : {
						op : "save",
						data: JSON.stringify(data)
					}
				}).done(function (response) {
					var result = JSON.parse(response);
					$("#user_edit").dialog("close");
					userId = null;
					if (result.success) {
						var link = $("#users_list a[id=" + data.id+ "]");
						if (link.length == 0) 
							$("#users_list").append("<a href='javascript:void(0)' id='" + data.id + "' class='user-link'>" + data.login + "</a>");
						else 
							link.html(data.login);
					}
					else 
						alert("Ошибка при сохранении: " + result.error);
				});
			}

			function deleteUser() {
				if (confirm("Вы уверены, что хотите удалить пользователя?")) {
					$.ajax({
						method:"POST",
						url:"include/user_controller.php",
						data: {
							op:"delete",
							id:userId
						}
					}).done(function (response) {
						var result = JSON.parse(response);
						if (result.success) {
							$("#user_edit").dialog("close");
							$("#users_list a[id=" + userId + "]").remove();
							userId = null;
						}
						else 
						alert("Ошибка при удалении: " + result.error);
					});
				}
			}
		</script>
	</head>
	<body>
    <table width="100%">
        <tr><td width="15%" valign="top">

                <?php include ("include/menu.php"); ?>
            </td><td width="70%" align="center"  valign="top">
		<div class="main">
			<b>Пользователи:</b><br/>
			<div id="users_list">
			<?php while($user = mysql_fetch_object($request)) { ?>
				<a href="javascript:void(0)" class="user-link" id="<?= $user -> user_id ?>"><?=$user -> user_login ?></a><br/>
			<?php } ?>
			</div>
			<br/>
			<button id="create-user">Создать</button>
		</div>
		
		<div id="user_edit">
			<table width="100%">
				<tr>
					<th width="50%">Логин: <span style="color:red">*</span></th>
					<td><span id="user-login" class="editable_single"></span><span id="login-error" style="display:none; color:red"><br/>Введите логин</span></td>
				</tr>
				<tr id="change_pass">
					<th>
						Пароль: <span style="color:red">*</span>
					</th>
					<td>
						<button id="change-pass">Задать пароль</button>
						<input type='password' id='pass' />
						<span id="pass-error" style="display:none; color:red"><br/>Введите пароль</span>						
					</td>
				</tr>
				<tr id="confirm_pass" style="display:none">
					<th>Подтвердите пароль: <span style="color:red">*</th>
					<td><input type='password' id="confirm" /><span id="confirm-error" style="display:none; color:red"><br/>Пароли не совпадают</span></td>
				</tr>
				<tr><th>Администратор:</th><td><select id="is_admin"><option value='0'>Нет</option><option value="1">Да</option></select></td></tr>
				<tr><td align="left"><button id="save-user">Сохранить</button></td><td align="right"><button id="delete-user">Удалить</button></td></tr>
			</table>
		</div>
            </td>
            <td width="15%"></td>
        </tr>
    </table>
	</body>


